﻿using UnityEngine;
using System.Collections;

namespace Helper{
	public enum TriggerType{
		SPHERE, CUBE
	}
	public class TargetTrigger : MonoBehaviour {
		//delegate void TargetTriggerEventHandle(Vector3 offsetPosition, Vector3 scaleOfRange);
		//event TargetTriggerEventHandle tte;


		[SerializeField] string targetName = "Sys_Player";
		public GameObject target;
		[SerializeField] TriggerType triggerType;
		[SerializeField] Vector3 offsetPos = Vector3.zero;
		[SerializeField] Vector3 rangeScale = new Vector3(1f, 1f, 1f);
		float radius{
			get{ return rangeScale.x;}
		}

		public bool IsInRange{
			get{ 
				switch (triggerType) {
				case TriggerType.SPHERE:
					return IsInSphere ();
					break;
				case TriggerType.CUBE:
					return IsInCube ();
					break;
				default:
					return false;
					break;
				}
			}
		}


		void Start(){
			ItemFlag iFlag = ItemManager.GetItemFlag (targetName);
			if (iFlag == null) {
				Debug.LogError ("No ItemFlag named " + targetName);
			}
			target = iFlag.gameObject;
		}

		void FixedUpdate(){
			if (IsInRange) {
				SendMessage ("OnTargetTriggerStay", target, SendMessageOptions.DontRequireReceiver);
			}
		}

		void OnDrawGizmos(){
			//tte (transform.position + offsetPos, rangeScale);
			//tte += DrawCube;
			switch (triggerType) {
			case TriggerType.SPHERE:
				DrawSphere (transform.position + offsetPos, rangeScale);
				break;
			case TriggerType.CUBE:
				DrawCube (transform.position + offsetPos, rangeScale);
				break;
			default:
				break;
			}
		}


		void DrawSphere(Vector3 pos, Vector3 scale){
			if (scale.y != 1f) {
				Gizmos.DrawSphere (pos, scale.x);
			} else {
				Gizmos.DrawWireSphere (pos, scale.x);
			}
		}
		void DrawCube(Vector3 pos, Vector3 size){
			Gizmos.DrawWireCube (pos, size);
		}

		bool IsInSphere(){
			return (Vector3.Distance (target.transform.position, transform.position + offsetPos) <= radius);
		}
		bool IsInCube(){
			Vector3 dir = target.transform.position - transform.position;
			dir /= 2f;
			return (Mathf.Abs (dir.x) <= rangeScale.x && Mathf.Abs (dir.y) <= rangeScale.y && Mathf.Abs (dir.z) <= rangeScale.z);
		}
	}
}
